-- KEYS[1] : 滑动窗口 key (zset)
-- ARGV[1]: 容量
-- ARGV[2]: 窗口时长(ms)
-- ARGV[3]: 唯一请求标识(UUID)

local key       = KEYS[1]
local capacity  = tonumber(ARGV[1])
local window    = tonumber(ARGV[2])
local uuid      = ARGV[3]

local now = redis.call("TIME")        -- 秒+微秒
now = now[1] * 1000 + math.floor(now[2] / 1000)

-- 清理过期成员
redis.call("ZREMRANGEBYSCORE", key, 0, now - window)

local current = redis.call("ZCARD", key)
if current < capacity then
    redis.call("ZADD", key, now, uuid)
    redis.call("EXPIRE", key, math.ceil(window / 1000))
    return1
end
return 0